<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>H5图片canvas压缩</title>
</head>
<body>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>

<input type="file" onChange="upload(this)" />

<script>
	//把图片转换成blob对象
	function convert(progress)tBase64UrlToBlob(urlData){
        let bytes=window.atob(urlData.split(',')[1])
	    let imgBuffer = new ArrayBuffer(bytes.length)
	    let ia = new Uint8Array(imgBuffer)
        for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i)
        }
        return new Blob([imgBuffer], {type : 'image/jpeg'})
    }
    //开始上传
	function upload(e) {
	    var that =this
	    var file = e.files[0]
	    var url = URL.createObjectURL(file)
	    var fileSize=file.size
	    var fileType=file.type
	    var fileName=file.name
	    var imgObject = new Image()
	    imgObject.src = url
	    imgObject.onload = function() {
	        //生成图片大小
	        var width = imgObject.width,
	            height = imgObject.height,
	            scale = width / height;
	            width = parseInt(1000);
	            height = parseInt(width/scale);
	        //生成canvas
	        $('body').append('<canvas id="canvas"></canvas>')
	        $('#canvas').css({display:'none'})
	        var canvas = $('#canvas');
	        var ctx = canvas[0].getContext('2d')
	        canvas.attr({width : width, height : height})
	        //旋转90度
	        // ctx.translate(width * 0.5, height * 0.5);
	        // ctx.rotate(Math.PI * 0.5);
	        // ctx.translate(-height * 0.5, -width * 0.5);
	        ctx.drawImage(imgObject, 0, 0, width, height)
	        var quality=0.5 //设置压缩质量
	        var base64 = canvas[0].toDataURL('image/jpeg',quality)
			var imgBlob=convertBase64UrlToBlob(base64)
			console.log(imgBlob);
			var form = new FormData();
			form.append('idcard', imgBlob)
			form.append('usrname','cj')
			form.append('age', '34')

	        // $.ajax({
	        // 	cache: false, 
	        // 	processData: false,
	        // 	contentType: false,
	        // 	type: "POST",
	        // 	url: "/uploadIdCard",
	        // 	data: form,
	        // 	success: function(result){
	               
	        // 	}
	        // })
	    }
	}
</script>
	
</body>
</html>